<template>
  <div class="app-container legal-wrap">
    <dynamic-legal-create
      ref="dynamicLegal"
      v-model="legalParam"
      :hide-required-asterisk="false"
      :rules="rules"
      :default-list="defaultList"
      :constructions="comLegalConstruction"
      :flow-structure="processDetail"
      :last-template="lastTemplate"
      :download-loading="downloadLoading"
      @setSupplierAccount="setSupplierAccount"
      @showTemplateDrawer="showTemplateDrawer"
      @showPreviewDrawer="showPreviewDrawer"
      @downloadTemplate="downloadTemplate"/>
    <!-- 关联合同 -->
    <ContractRelevance ref="contractRelevanceRef" v-model="legalParam.contractList" />
    <audit-process
      ref="auditProcess"
      :old-audit-info="legalDetail.oldAduitInfo"
      :default-aduitor-list="[proposer]"
      v-model="legalParam.aduitInfo"
      :flow-structure="processDetail"
      :is-modify="Boolean(remodifyId)"
      :disable="Boolean(remodifyId)"
      :is-modify-form="Number(isModifyForm)"
      :current-process-index="Number(currentProcessIndex)"
      @submit="submitFun"
      @getProcess="getProcess"
    />
    <fixed-pagination>
      <div class="center">
        <el-button v-if="!legalId" type="info" size="small" class="back-btn empty-btn-style" @click="toBackStep">上一步</el-button>
        <el-button v-if="setSubmitStatus()" type="primary" size="small" class="submit-btn" @click="submit()">发起审批</el-button>
        <el-button v-if="setSaveDraftStatus()" type="info" size="small" class="back-btn empty-btn-style" @click="saveDraft">保存草稿</el-button>
        <el-button type="info" size="small" class="back-btn cancel-btn-style" @click="toBack">返回列表</el-button>
      </div>
    </fixed-pagination>
    <ContractTemplate
      ref="contractTemplateRef"
      :contract-type="type"
      :preview-path="previewPath"
      :download-loading="downloadLoading"
      @downloadTemplate="downloadTemplate" />
    <ContractPreview
      ref="ContractPreviewRef"
      :file-data="lastTemplate"
      :preview-path="previewPath"
      :download-loading="downloadLoading"
      :show-footer="false"
      is-fill
      @setDownloadParams="downloadPreviewFile"/>
    <SelectSupplierAccount ref="supplierAccountRef" @fillAccount="fillAccount" />
  </div>
</template>
<script>
import DynamicLegalCreate from '../module/dynamicLegalCreate';
import ContractRelevance from '../module/contractRelevance';
import SelectSupplierAccount from '../module/selectSupplierAccount';
import AuditProcess from '@/components/Common/auditProcess';
import ContractTemplate from '@/components/legal/contractTemplate/index';
import ContractPreview from '@/components/legal/contractTemplate/contractPreview';
import Title from '@/components/Title';
import Common from '../mixins/common';
import { eCommerceLegalConstruct as legalConstruction } from '../model/legalConstruction';
import { eCommerceLegalRules } from '../model/legalRules';
import { showModal } from '@/utils/message';
export default {
  name: 'ECommerceLegal',
  components: { DynamicLegalCreate, AuditProcess, Title, ContractTemplate, ContractPreview, ContractRelevance, SelectSupplierAccount },
  mixins: [
    Common
  ],
  props: {
    legalDetail: {
      type: Object | String,
      default: () => null
    },
    type: {
      type: String | Number,
      default: ''
    }
  },
  data() {
    return {
      eCommerceLegalRules,
      legalParam: {
        createInfo: {
          createrDepartment: '',
          creater: '',
          createrPost: '',
          createrId: '',
          createrDepartmentId: '',
          proposer: null,
          proposerAvatar: '',
          proposerId: '',
          departmentId: '',
          post: '--',
          flowCode: ''
        },
        contractInfo: {
          type: '',
          name: '',
          tempSource: '',
          subject: '',
          oppCompany: '',
          deadline: '',
          attachment: [],
          businessLicense: [],
          describe: '',
          depositBank: '',
          accountName: '',
          accountNumber: '',
          contactPerson: '',
          contactPhone: '',
          supplierAddress: '',
          cooperModel: {
            type: '',
            name: ''
          },
          accountPeriod: {
            type: '',
            name: ''
          },
          // contractCodes: [{ code: '' }],
          ourStamp: '',
          legalTemplate: '',
          stampType: ''
        },
        submitType: 2,
        aduitInfo: {
          countersignSet: 0,
          process: [],
          senders: []
        },
        contractList: [], // 关联合同列表
        merchandiseInfos: [
          {
            contractCode: [{ code: '' }], // 关联合同编号
            productName: '', // 产品名称
            productSpecification: '', // 产品规格
            productSpecificationCode: '', // 产品规格编码
            unitPrice: '', // 分销/批采单价
            purchaseNum: '', // 采购数量
            retailPriceRange: '', // 零售价区间
            commissionRatio: '', // 佣金比例
            isFreeShipping: 0, // 是否包邮
            postageDesc: '', // 邮费说明
            deliveryAddress: '', // 发货地
            deliveryPrescription: '', // 发货时效
            expressCompany: '', // 快递
            remark: '', // 备注
            specsFile: { // 规格附件
              attachment: []
            },
            productFile: { // 产品图片
              attachment: []
            },
            businessLicense: { // 营业执照
              attachment: []
            },
            powerOfAttorney: { // 授权书
              attachment: []
            },
            trademarkFile: { // 商标信息
              attachment: []
            },
            trademarkLicense: { // 商标注册证
              attachment: []
            },
            hygienicLicense: { // 卫生许可证
              attachment: [],
              effectiveDate: ''
            },
            productionLicense: { // 食品/化妆品生产许可证
              attachment: [],
              effectiveDate: ''
            },
            distributionLicense: { // 食品流通许可证
              attachment: [],
              effectiveDate: ''
            },
            foodBusinessLicense: { // 食品经营许可证
              attachment: [],
              effectiveDate: ''
            },
            printBusinessLicense: { // 出版物经营许可证
              attachment: [],
              effectiveDate: ''
            },
            otherAttachment: { // 其他
              attachment: [],
              effectiveDate: ''
            },
            inspectionReport: {
              attachment: [],
              effectiveDate: ''
            },
            cccCertificate: {
              attachment: [],
              effectiveDate: ''
            },
            businessPermit: {
              attachment: [],
              effectiveDate: ''
            },
            recordAttachment: {
              attachment: [],
              effectiveDate: ''
            },
            trustAgreement: {
              attachment: [],
              effectiveDate: ''
            },
            accountOpeningCertificate: {
              attachment: [],
              effectiveDate: ''
            },
            customsDeclaration: {
              attachment: [],
              effectiveDate: ''
            },
            unsetKey: {
              attachment: [],
              effectiveDate: ''
            }
          }
        ]
      },
      defaultList: {
        'createInfo.proposer': []
      },
      comLegalConstruction: []
    };
  },
  computed: {
    /* comLegalConstruction() {
      return legalConstruction(this.legalConstructionArg);
    }, */
    rules() {
      return this.eCommerceLegalRules;
    }
  },
  created() {
    this.comLegalConstruction = JSON.parse(JSON.stringify(legalConstruction(this.legalConstructionArg)));
  },
  methods: {
    submitFun(senders = []) {
      this.modifySenders = senders;// 存到mixins
      var timestamp = Date.parse(new Date());
      if (timestamp - this.antiShakeTime < 600) {
        return;
      }
      this.antiShakeTime = timestamp;
      const params = JSON.parse(JSON.stringify(this.legalParam));
      if (this.reapplyId) {
        params.submitType = 3;
        params.byReapplyId = this.legalId;
      } else {
        params.submitType = 2;
        if (params.hasOwnProperty('byReapplyId')) delete params.byReapplyId;
      }
      this.remodifyId && (params.byRemodifyId = this.remodifyId);
      params.orders = this.orderPriceSwitch(this.orders, 2);
      delete params.createInfo.creater;
      delete params.createInfo.createrDepartment;
      delete params.createInfo.proposer;
      if (this.isSigner === 0) {
        params.aduitInfo = this.removeSigner(params.aduitInfo);
      }
      const message = (this.legalId && !this.createNew && !this.setSaveDraftStatus()) ? '合同修改成功' : '合同新建成功';
      if (this.legalId && !this.createNew) {
        this.handleModifyData(params);
      }
      this.handlePost(params, message);
    },
    setSupplierAccount(supplierAccounts, callbackFun) {
      if (supplierAccounts.length === 1) {
        const accountField = ['accountNumber', 'accountName', 'depositBank', 'contactPerson', 'contactPhone', 'supplierAddress'];
        const isNotEmpty = accountField.some(i => {
          const curData = this.legalParam.contractInfo[i];
          if (curData || curData === 0) {
            return true;
          }
          return false;
        });
        if (isNotEmpty) {
          showModal('是否自动填写签约对方的收款账户信息', '', {}, true).then(_ => {
            this.fillAccount(supplierAccounts[0]);
            if (callbackFun) callbackFun();
          }).catch(() => {
            if (callbackFun) callbackFun();
          });
        } else {
          this.fillAccount(supplierAccounts[0]);
        }
      } else if (supplierAccounts.length > 1) {
        this.$refs.supplierAccountRef.openDialog(supplierAccounts);
      }
    },
    // 填充签约对方的收款信息
    fillAccount(data) {
      // "收款信息"中的字段 对应 "电商产品购销类"的字段
      const accountToECommerce = {
        payNum: 'accountNumber', // 收款账号 => 银行账号
        payName: 'accountName', // 收款户名 => 户名
        subBank: 'depositBank', // 支行 => 对方开户行
        contactPerson: 'contactPerson', // 对方联系人 => 对方联系人
        tel: 'contactPhone', // 联系人电话 => 联系人电话
        province: 'supplierAddress' // 地址 => 供应商地址
      };
      for (const key of Object.keys(accountToECommerce)) {
        if (data[key] || data[key] === 0) {
          this.$set(this.legalParam.contractInfo, accountToECommerce[key], data[key]);
        }
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.legal-wrap {
  .footer-btn-wrap {
    display: flex;
    justify-content: center;
  }
  .module-box {
    // margin-bottom: 40px;
    padding-bottom: 32px;
  }
}
.empty-btn-style {
  border-color: #406EFF;
  background: #fff;
  color: #406EFF;
  width: 80px;
  padding: 7px 0;
  text-align: center;
}
::v-deep .el-form-item__error {
  padding-top: 2px !important;
}
</style>
